package com.itboye.sunsun.luntan;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.itboye.sunsun.adapter.LunTanDetailAdapter;
import com.itboye.sunsun.adapter.LuntanDetileAdapter;
import com.itboye.sunsun.beans.LunTanHomePageBean;
import com.itboye.sunsun.beans.LunTanHomePageBean.LunTanItemBean;
import com.itboye.sunsun.custome.XListView;
import com.itboye.sunsun.custome.XListView.IXListViewListener;
import com.itboye.sunsun.network.HttpRequest;
import com.itboye.sunsun.support.BaseFragment;
import com.itboye.sunsun.volley.MyJsonRequest;
import com.itboye.sunsun.volley.XErrorListener;
import com.itboye.sunsun.volley.XRequestListener;
import com.itboye.sunsunhome.R;

import java.util.ArrayList;
import java.util.List;

public class MyFragment extends BaseFragment implements OnClickListener {
	// TextView tv;
	String text;

	ImageView back;
	TextView title;
	XListView xlistview;
	ImageView edit;
	// TextView title;
	String fid;
	private int pageNum = 1;

	private int type = 0;
	BaseAdapter adapter;
	List<LunTanItemBean> dataList = new ArrayList<>();
	LinearLayout headViewContainer;

	public MyFragment(String text, String fid) {
		this.text = text;
		this.fid = fid;
	}

	public MyFragment(String text, String fid, int type) {
		this.text = text;
		this.fid = fid;
		this.type = type;
	}

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

		return inflater.inflate(R.layout.activity_luntan_detail, null);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		IntentFilter filter = new IntentFilter("refresh");
		getActivity().registerReceiver(receiver, filter);
		
		IntentFilter filterr = new IntentFilter("refreshisbuttn");
		getActivity().registerReceiver(refreshisbuttn, filterr);
		initView();
		showProgressDialog("数据正在加载中，请稍后", true);
		title.setText(text);
		if (this.type == 0)
			getView().findViewById(R.id.topbar).setVisibility(View.GONE);
		getHeaderData();
		pullDown();
	}

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			System.out.println("44444444444444444444444444444444");
			digest = intent.getStringExtra("digest");
			if (digest != null) {

			} else {
				digest="0";
			}
			pullDown();
		}
	};
	
	BroadcastReceiver refreshisbuttn = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			System.out.println("333333333333333333333333333333333333333333333");
			digest = intent.getStringExtra("digest");
			dataList.clear();
			if (digest != null) {

			} else {
				digest="1";
				
			}
			pullDown();
		}
	};

	private String digest = "0";

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		// pullDown();
	}

	private void getHeaderData() {
		MyJsonRequest.Builder<LunTanHomePageBean> builder = new MyJsonRequest.Builder<LunTanHomePageBean>()
				.param("fid", fid).apiVer("100").param("page_no", "1")
				.param("page_size", 3).param("fup", fid)
				.param("fup","1")
				.typeKey("BY_ForumThread_query").param("stick", 1)// BY_Forumforum_query
				.requestListener(new XRequestListener<LunTanHomePageBean>() {

					@Override
					public void onResponse(LunTanHomePageBean orderBean) {
						if (orderBean.getCount() < 1) {
							return;
						}
						List<LunTanItemBean> list = orderBean.getList();
						headViewContainer = new LinearLayout(getActivity());
						headViewContainer.setOrientation(LinearLayout.VERTICAL);

						for (final LunTanItemBean lunTanItemBean : list) {
							View v = getActivity().getLayoutInflater().inflate(
									R.layout.item_top_tiezi, headViewContainer,
									false);
							((TextView) v.findViewById(R.id.textview))
									.setText(lunTanItemBean.getSubject());
							headViewContainer.addView(v);
							v.setOnClickListener(new OnClickListener() {

								@Override
								public void onClick(View v) {
									Intent intent = new Intent(getActivity(),
											TieZiDetailActivity.class);

									intent.putExtra("fid",
											lunTanItemBean.getFid());
									intent.putExtra("tid",
											lunTanItemBean.getTid());

									intent.putExtra("author",
											lunTanItemBean.getAuthor());
									intent.putExtra("author_id",
											lunTanItemBean.getAuthorId());
									intent.putStringArrayListExtra("img",
											lunTanItemBean.getImg());
									startActivity(intent);

								}
							});
						}

						xlistview.addHeaderView(headViewContainer);

					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {

					}
				});

		MyJsonRequest<LunTanHomePageBean> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	/***
	 * 2016.9.23增加精华帖、非精华帖查看
	 */
	private void pullDown() {
		
		pageNum = 1;
		MyJsonRequest.Builder<LunTanHomePageBean> builder = new MyJsonRequest.Builder<LunTanHomePageBean>()
				.param("fid", fid).apiVer("100").param("page_no", "" + pageNum)
				.param("digest", digest).typeKey("BY_ForumThread_query")
				// .param("stick", 3)
				.requestListener(new XRequestListener<LunTanHomePageBean>() {

					@Override
					public void onResponse(LunTanHomePageBean orderBean) {
						// onPullDownFinish(adapter, xlistview, orderBean);
						if(pageNum==1){
							dataList.clear();
						}
						if (adapter == null) {
							adapter = new LuntanDetileAdapter(dataList,
									getActivity());
							xlistview.setAdapter(adapter);

						}

						if (orderBean.getCount() > 0) {
							dataList.clear();
							dataList.addAll(orderBean.getList());
							adapter.notifyDataSetChanged();
						}

						pageNum++;
						xlistview.stopLoadMore();
						xlistview.stopRefresh();
						try {
							closeProgressDialog();
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						xlistview.stopLoadMore();
						xlistview.stopRefresh();
						try {
							closeProgressDialog();

						} catch (Exception e) {
							// TODO: handle exception
						}
						// onPullDownError(adapter, xlistview, exception, code,
						// msg);
					}
				});

		MyJsonRequest<LunTanHomePageBean> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);

	}

	protected void pullUp() {
		MyJsonRequest.Builder<LunTanHomePageBean> builder = new MyJsonRequest.Builder<LunTanHomePageBean>()
				.param("fid", fid).apiVer("100").param("page_no", "" + pageNum).param("digest", digest)
				.typeKey("BY_ForumThread_query")
				.requestListener(new XRequestListener<LunTanHomePageBean>() {

					@Override
					public void onResponse(LunTanHomePageBean orderBean) {
						// onPullUpFinish(adapter, xlistview, orderBean);
						if (adapter == null) {
							adapter = new LunTanDetailAdapter(dataList,
									getActivity());
							xlistview.setAdapter(adapter);

						}

						if (orderBean.getCount() > 0) {
							dataList.addAll(orderBean.getList());
							adapter.notifyDataSetChanged();
						}

						pageNum++;
						xlistview.stopLoadMore();
						xlistview.stopRefresh();
						try {
							closeProgressDialog();
						} catch (Exception e) {
						}
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						xlistview.stopLoadMore();
						try {
							closeProgressDialog();
						} catch (Exception e) {
						}
						// onPullUpError(adapter, xlistview, exception, code,
						// msg);
					}
				});

		MyJsonRequest<LunTanHomePageBean> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);

	}

	private void initView() {

		// getView().findViewById(R.id.back).setOnClickListener(new
		// OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		//
		// getActivity().finish();
		// }
		// });

		// title.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		//
		// }
		// });

		xlistview.setPullRefreshEnable(true);
		xlistview.setPullLoadEnable(true);
		xlistview.setXListViewListener(new IXListViewListener() {

			@Override
			public void onRefresh() {
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						pullDown();
						xlistview.stopLoadMore();
						xlistview.stopRefresh();
					}
				}, 2000);
			}

			@Override
			public void onLoadMore() {
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						pullUp();
						xlistview.stopLoadMore();
						xlistview.stopRefresh();
					}
				}, 2000);

			}

		});

		xlistview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (headViewContainer != null) {
					if (position < 2) {
						return;
					}

					position -= 2;
				} else if (headViewContainer == null) {
					if (position < 1) {
						return;
					}

					position--;
				}

				Intent intent = new Intent(getActivity(),
						TieZiDetailActivity.class);
				LunTanItemBean bean = dataList.get(position);
				intent.putExtra("fid", bean.getFid());
				intent.putExtra("tid", bean.getTid());

				intent.putExtra("author", bean.getAuthor());
				intent.putExtra("author_id", bean.getAuthorId());
				intent.putStringArrayListExtra("img", bean.getImg());
				// intent.putExtra("pid", "");
				// intent.putExtra("what", bean);
				startActivity(intent);

			}
		});

		// getView().findViewById(R.id.edit).setOnClickListener(new
		// OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// Intent intent = new Intent(getActivity(),
		// FaBiaoTieZiActivity.class);
		//
		// intent.putExtra("fid", fid);
		//
		// startActivity(intent);
		// }
		// });
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back:
			getActivity().finish();
			break;
		case R.id.edit:
			Intent intent = new Intent(getActivity(), FaBiaoTieZiActivity.class);

			intent.putExtra("fid", fid);

			startActivity(intent);
		default:
			break;
		}

	}
}
